<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能运动姿势分析播放器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
            padding: 30px;
        }
        
        .video-section {
            position: relative;
        }
        
        .video-container {
            position: relative;
            background: #000;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        
        #videoPlayer {
            width: 100%;
            height: auto;
            display: block;
        }
        
        .video-overlay {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 15px;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .timeline-container {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 15px;
        }
        
        .timeline {
            position: relative;
            height: 60px;
            background: #e0e0e0;
            border-radius: 30px;
            overflow: visible; /* 改为visible确保标记可见 */
            margin: 10px 0;
            border: 2px solid #ddd; /* 添加边框让时间轴更明显 */
        }
        
        .timeline-marker {
            position: absolute;
            top: -2px; /* 稍微突出时间轴边界 */
            width: 6px; /* 增加宽度让标记更明显 */
            height: calc(100% + 4px); /* 高度稍微超出时间轴 */
            cursor: pointer;
            transition: all 0.3s ease;
            border-radius: 3px; /* 添加圆角 */
            z-index: 5; /* 确保在时间轴之上 */
        }
        
        .timeline-marker:hover {
            transform: scaleX(2);
            z-index: 10;
        }
        
        .timeline-marker.problem { background: #f44336; }
        .timeline-marker.critical-issue { background: #f44336; }
        .timeline-marker.minor-issue { background: #ff9800; }
        .timeline-marker.key-moment { background: #2196F3; }
        .timeline-marker.slow-motion { background: #ff9800; }
        .timeline-marker.slow-motion-start { background: #4CAF50; }
        .timeline-marker.slow-motion-end { background: #4CAF50; }
        
        .controls {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 20px;
        }
        
        .control-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            color: white;
        }
        
        .control-btn.play { background: #4CAF50; }
        .control-btn.pause { background: #ff9800; }
        .control-btn.slow { background: #2196F3; }
        .control-btn.normal { background: #9C27B0; }
        
        .control-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        
        .analysis-panel {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            height: fit-content;
        }
        
        .panel-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 20px;
            text-align: center;
            font-weight: 600;
        }
        
        .problem-frame {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 5px solid #f44336;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .problem-frame:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        }
        
        .problem-frame.severity-high { border-left-color: #f44336; }
        .problem-frame.severity-medium { border-left-color: #ff9800; }
        .problem-frame.severity-low { border-left-color: #ffeb3b; }
        
        .frame-time {
            font-weight: 600;
            color: #2196F3;
            font-size: 14px;
        }
        
        .frame-issue {
            font-weight: 600;
            color: #f44336;
            margin: 8px 0;
        }
        
        .frame-improvement {
            color: #666;
            font-size: 14px;
            line-height: 1.5;
        }
        
        .slow-motion-guide {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-top: 20px;
            border-left: 5px solid #ff9800;
        }
        
        .guide-title {
            font-weight: 600;
            color: #ff9800;
            margin-bottom: 10px;
        }
        
        .focus-points {
            list-style: none;
        }
        
        .focus-points li {
            padding: 5px 0;
            padding-left: 20px;
            position: relative;
        }
        
        .focus-points li:before {
            content: "→";
            position: absolute;
            left: 0;
            color: #ff9800;
            font-weight: bold;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .error {
            text-align: center;
            padding: 50px;
            color: #f44336;
            background: #ffebee;
            border-radius: 10px;
            margin: 20px;
        }
        
        .input-section {
            text-align: center;
            padding: 40px;
            background: #f8f9fa;
            border-radius: 15px;
            margin: 20px;
        }
        
        .input-group {
            margin: 15px 0;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        
        .input-group input, .input-group select {
            padding: 12px 20px;
            border: 2px solid #ddd;
            border-radius: 25px;
            font-size: 16px;
            width: 300px;
            max-width: 100%;
        }
        
        .load-btn {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 20px;
            transition: all 0.3s ease;
        }
        
        .load-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-left: 8px;
        }
        
        .status-indicator.high { background: #f44336; }
        .status-indicator.medium { background: #ff9800; }
        .status-indicator.low { background: #ffeb3b; }
        .status-indicator.good { background: #4CAF50; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎯 智能运动姿势分析播放器</h1>
            <p>自动识别问题帧，智能慢放指导，专业改进建议</p>
            <small style="opacity: 0.8; font-size: 14px;">
                📡 连接到: localhost:8085 | 🎥 视频分析: localhost:5000
            </small>
        </div>
        
        <div id="inputSection" class="input-section">
            <h2>加载分析结果</h2>
            <div class="input-group">
                <label for="token">认证Token:</label>
                <input type="password" id="token" placeholder="输入JWT认证token" />
                <small style="color: #666; display: block; margin-top: 5px;">
                    💡 获取token: POST localhost:8085/uaa/auth/login 登录后获得，或使用下方快速登录
                </small>
            </div>
            <div class="input-group">
                <label for="resultId">分析结果ID:</label>
                <input type="text" id="resultId" placeholder="输入视频分析结果ID" />
            </div>
            <div class="input-group">
                <label for="sportType">运动类型:</label>
                <select id="sportType">
                    <option value="running">跑步</option>
                    <option value="basketball_shooting">篮球投篮</option>
                    <option value="tennis_serve">网球发球</option>
                    <option value="golf_swing">高尔夫挥杆</option>
                    <option value="swimming">游泳</option>
                </select>
            </div>
            <div style="margin-top: 15px;">
                <button class="load-btn" onclick="loadVideoAnalysis()">🚀 加载智能分析</button>
                <button class="load-btn" onclick="testLogin()" style="background: #2196F3; margin-left: 10px;">🔑 测试登录</button>
                <button class="load-btn" onclick="testSmartPlayback()" style="background: #FF9800; margin-left: 10px;">🎬 测试智能播放</button>
                <button class="load-btn" onclick="openAiGuidance()" style="background: #9C27B0; margin-left: 10px;">🤖 AI教练指导</button>
            </div>
            
            <div style="margin-top: 15px; padding: 10px; background: #fff3e0; border-radius: 8px; font-size: 14px;">
                <strong>💡 使用提示：</strong><br>
                • <strong>🎬 测试智能播放</strong> - 可以直接预览智能播放功能，包括时间轴标记、问题帧列表、智能暂停和慢放<br>
                • <strong>🚀 加载智能分析</strong> - 需要先输入Token和结果ID来加载真实的分析数据<br>
                • <strong>📤 视频上传</strong> - 可以直接上传视频进行最高精度分析
            </div>
            
            <div style="margin-top: 20px; padding-top: 20px; border-top: 2px solid #eee;">
                <h4 style="color: #666; margin-bottom: 15px;">📤 视频上传分析</h4>
                <div class="input-group">
                    <label for="videoFile">选择视频文件:</label>
                    <input type="file" id="videoFile" accept="video/*" style="padding: 8px; margin-bottom: 10px;" />
                    <button class="load-btn" onclick="uploadVideo()" style="background: #4CAF50;">📤 上传并分析</button>
                </div>
                <div id="uploadProgress" style="display: none; margin-top: 10px;">
                    <div style="background: #f0f0f0; border-radius: 10px; overflow: hidden;">
                        <div id="progressBar" style="height: 4px; background: #4CAF50; width: 0%; transition: width 0.3s;"></div>
                    </div>
                    <div id="uploadStatus" style="margin-top: 5px; color: #666; font-size: 14px;"></div>
                </div>
            </div>
            
            <div style="margin-top: 20px; padding-top: 20px; border-top: 2px solid #eee;">
                <h4 style="color: #666; margin-bottom: 15px;">🔑 快速登录获取Token</h4>
                <div class="input-group" style="display: inline-block; margin-right: 10px;">
                    <input type="text" id="username" placeholder="用户名" style="width: 150px;" />
                </div>
                <div class="input-group" style="display: inline-block; margin-right: 10px;">
                    <input type="password" id="password" placeholder="密码" style="width: 150px;" />
                </div>
                <button class="load-btn" onclick="quickLogin()" style="background: #4CAF50;">🚀 快速登录</button>
            </div>
        </div>
        
        <div id="loadingSection" class="loading" style="display: none;">
            <h3>🔄 正在加载视频和分析数据...</h3>
            <p>请稍候，我们正在准备您的智能播放器</p>
        </div>
        
        <div id="errorSection" class="error" style="display: none;">
            <h3>❌ 加载失败</h3>
            <p id="errorMessage"></p>
        </div>
        
        <div id="mainContent" class="main-content" style="display: none;">
            <div class="video-section">
                <div class="video-container">
                    <video id="videoPlayer" controls preload="metadata" style="width: 100%; max-height: 400px;">
                        您的浏览器不支持视频播放
                    </video>
                    <div class="video-overlay">
                        <div id="currentFrame">帧: 0</div>
                        <div id="currentTime">时间: 0.00s</div>
                        <div id="playbackSpeed">速度: 1.0x</div>
                    </div>
                </div>
                
                <div class="timeline-container">
                    <h4>📊 智能时间轴</h4>
                    <div class="timeline" id="timeline"></div>
                    <div class="controls">
                        <button class="control-btn play" onclick="playVideo()">▶️ 播放</button>
                        <button class="control-btn pause" onclick="pauseVideo()">⏸️ 暂停</button>
                        <button class="control-btn slow" onclick="setSpeed(0.25)">🐌 0.25x</button>
                        <button class="control-btn slow" onclick="setSpeed(0.5)">🚶 0.5x</button>
                        <button class="control-btn normal" onclick="setSpeed(1.0)">🏃 1.0x</button>
                        <button class="control-btn" onclick="debugTimeline()" style="background: #FF5722;">🔧 调试时间轴</button>
                    </div>
                </div>
            </div>
            
            <div class="analysis-panel">
                <h3 class="panel-title">🎯 问题帧分析</h3>
                <div id="problematicFrames"></div>
                
                <div class="slow-motion-guide">
                    <h4 class="guide-title">🎬 慢放指导</h4>
                    <div id="slowMotionGuide"></div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let videoPlayer;
        let playerConfig;
        let currentResultId;
        let currentSportType;
        
        function loadVideoAnalysis() {
            const token = document.getElementById('token').value;
            const resultId = document.getElementById('resultId').value;
            const sportType = document.getElementById('sportType').value;
            
            if (!token) {
                alert('请输入认证Token');
                return;
            }
            
            if (!resultId) {
                alert('请输入分析结果ID');
                return;
            }
            
            currentResultId = resultId;
            currentSportType = sportType;
            
            showLoading();
            
            // 调用新的简化API获取详细分析结果
            fetch(`http://localhost:8085/api/video/result/${resultId}?sportType=${encodeURIComponent(sportType)}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 0) {
                        // 适配新API数据格式为智能播放器期望的格式
                        playerConfig = adaptNewApiToPlayerConfig(data.data, resultId);
                        initializePlayer();
                    } else {
                        showError('获取详细分析结果失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('API调用错误:', error);
                    showError('加载失败: ' + error.message);
                });
        }
        
        /**
         * 将新API的数据格式适配为智能播放器期望的格式
         */
        function adaptNewApiToPlayerConfig(apiData, resultId) {
            const detailedAnalysis = apiData.detailedAnalysis;
            
            // 从详细分析中提取问题帧
            const problematicFrames = [];
            const slowMotionSegments = [];
            
            if (detailedAnalysis && detailedAnalysis.movementPhases) {
                detailedAnalysis.movementPhases.forEach((phase, index) => {
                    const startTime = parseFloat(phase.timeRange ? phase.timeRange.split('-')[0] : index * 2);
                    const endTime = parseFloat(phase.timeRange ? phase.timeRange.split('-')[1] : (index + 1) * 2);
                    
                    // 判断是否为问题帧
                    const hasIssues = phase.issues && phase.issues.length > 0;
                    const severity = hasIssues ? (phase.issues.length > 2 ? '高' : '中') : '低';
                    
                    if (hasIssues || severity !== '低') {
                        problematicFrames.push({
                            frameId: index,
                            timestamp: startTime,
                            severity: severity,
                            issue: phase.keyCharacteristics || phase.phase || `阶段${index + 1}需要关注`,
                            improvement: phase.recommendations || '保持当前姿势并注意细节',
                            analysisDetails: phase.issues ? phase.issues.join('; ') : '暂无详细分析'
                        });
                        
                        // 为问题帧创建慢放片段
                        slowMotionSegments.push({
                            startTime: startTime,
                            endTime: endTime,
                            speed: severity === '高' ? 0.25 : 0.5,
                            reason: phase.keyCharacteristics || '关键动作分析',
                            guidance: phase.recommendations || '注意观察此阶段的动作细节'
                        });
                    }
                });
            }
            
            // 如果没有运动阶段数据，从关节分析中提取
            if (problematicFrames.length === 0 && detailedAnalysis && detailedAnalysis.jointAnalysis) {
                detailedAnalysis.jointAnalysis.forEach((joint, index) => {
                    if (joint.issues && joint.issues.length > 0) {
                        problematicFrames.push({
                            frameId: index,
                            timestamp: index * 3, // 每3秒一个关键点
                            severity: joint.issues.length > 1 ? '高' : '中',
                            issue: `${joint.jointName || '关节'}问题：${joint.issues[0]}`,
                            improvement: joint.recommendations || '调整姿势以改善关节角度',
                            analysisDetails: joint.issues.join('; ')
                        });
                        
                        slowMotionSegments.push({
                            startTime: index * 3,
                            endTime: (index + 1) * 3,
                            speed: 0.5,
                            reason: `${joint.jointName || '关节'}分析`,
                            guidance: joint.recommendations || '观察关节角度变化'
                        });
                    }
                });
            }
            
            // 如果仍然没有数据，生成一些测试数据以演示功能
            if (problematicFrames.length === 0) {
                console.log('⚠️ 没有分析数据，生成测试数据以演示智能播放功能');
                problematicFrames.push(
                    {
                        frameId: 0,
                        timestamp: 3,
                        severity: '高',
                        issue: '膝关节角度异常',
                        improvement: '保持膝关节轻微弯曲，避免过度伸展',
                        analysisDetails: '测试数据：膝关节角度超出正常范围'
                    },
                    {
                        frameId: 1,
                        timestamp: 8,
                        severity: '中',
                        issue: '摆臂幅度不足',
                        improvement: '增加手臂摆动幅度，保持节奏',
                        analysisDetails: '测试数据：手臂摆动范围偏小'
                    },
                    {
                        frameId: 2,
                        timestamp: 15,
                        severity: '中',
                        issue: '躯干前倾过度',
                        improvement: '保持躯干挺直，轻微前倾即可',
                        analysisDetails: '测试数据：躯干前倾角度过大'
                    }
                );
                
                slowMotionSegments.push(
                    {
                        startTime: 2,
                        endTime: 5,
                        speed: 0.25,
                        reason: '关键膝关节动作分析',
                        guidance: '仔细观察膝关节的屈伸过程'
                    },
                    {
                        startTime: 7,
                        endTime: 10,
                        speed: 0.5,
                        reason: '摆臂技术要点',
                        guidance: '注意手臂的摆动节奏和幅度'
                    }
                );
            }
            
            // 生成播放指令
            const playbackInstructions = [];
            const timelineMarkers = [];
            
            // 为问题帧生成暂停指令
            problematicFrames.forEach(frame => {
                playbackInstructions.push({
                    timestamp: frame.timestamp,
                    action: 'pause',
                    duration: frame.severity === '高' ? 3 : 2, // 高严重性暂停3秒，其他2秒
                    message: `⚠️ ${frame.issue} - ${frame.improvement}`,
                    priority: frame.severity
                });
                
                timelineMarkers.push({
                    timestamp: frame.timestamp,
                    type: frame.severity === '高' ? 'critical_issue' : 'minor_issue',
                    label: `问题帧 ${frame.frameId + 1}`,
                    description: frame.issue
                });
            });
            
            // 为慢放片段生成指令
            slowMotionSegments.forEach(segment => {
                playbackInstructions.push({
                    timestamp: segment.startTime,
                    action: 'slow',
                    speed: segment.speed,
                    message: `🎬 ${segment.reason} - ${segment.guidance}`,
                    priority: 'normal'
                });
                
                playbackInstructions.push({
                    timestamp: segment.endTime,
                    action: 'normal',
                    speed: 1.0,
                    message: '恢复正常播放速度',
                    priority: 'normal'
                });
                
                timelineMarkers.push({
                    timestamp: segment.startTime,
                    type: 'slow_motion_start',
                    label: '慢放开始',
                    description: segment.reason
                });
                
                timelineMarkers.push({
                    timestamp: segment.endTime,
                    type: 'slow_motion_end',
                    label: '慢放结束',
                    description: '恢复正常速度'
                });
            });
            
            // 按时间戳排序
            playbackInstructions.sort((a, b) => a.timestamp - b.timestamp);
            timelineMarkers.sort((a, b) => a.timestamp - b.timestamp);
            
            console.log('🎯 适配完成的智能播放数据:');
            console.log(`- 问题帧: ${problematicFrames.length} 个`);
            console.log(`- 慢放片段: ${slowMotionSegments.length} 个`);
            console.log(`- 播放指令: ${playbackInstructions.length} 个`);
            console.log(`- 时间轴标记: ${timelineMarkers.length} 个`);
            console.log('播放指令详情:', playbackInstructions);
            console.log('时间轴标记详情:', timelineMarkers);
            
            // 构建适配后的配置
            return {
                resultId: resultId,
                videoUrl: `/api/video/play/${resultId}`,
                summary: apiData.summary || '完成最详细专业分析',
                videoDisplayInfo: {
                    videoFileName: `result_${resultId}.mp4`,
                    videoUrl: `/api/video/play/${resultId}`,
                    problematicFrames: problematicFrames,
                    slowMotionSegments: slowMotionSegments,
                    analysisType: 'detailed',
                    recommendations: detailedAnalysis ? [
                        detailedAnalysis.personalizedCoaching?.overallRecommendation || '继续保持良好的运动习惯',
                        '关注标记的关键时间点',
                        '结合慢放片段进行细节观察'
                    ] : ['分析完成，请查看视频标记'],
                    statistics: {
                        totalFrames: problematicFrames.length,
                        highSeverityFrames: problematicFrames.filter(f => f.severity === '高').length,
                        mediumSeverityFrames: problematicFrames.filter(f => f.severity === '中').length,
                        lowSeverityFrames: problematicFrames.filter(f => f.severity === '低').length
                    }
                },
                playbackInstructions: playbackInstructions, // 智能播放指令
                timelineMarkers: timelineMarkers, // 时间轴标记
                smartPlayback: {
                    enabled: true,
                    pauseOnProblems: problematicFrames.length > 0,
                    slowMotionEnabled: slowMotionSegments.length > 0,
                    autoGuidance: true
                },
                detailedAnalysis: detailedAnalysis // 保留原始详细分析数据
            };
        }
        
        /**
         * 上传视频并进行分析
         */
        function uploadVideo() {
            const token = document.getElementById('token').value;
            const videoFile = document.getElementById('videoFile').files[0];
            
            if (!token) {
                alert('请先输入认证Token');
                return;
            }
            
            if (!videoFile) {
                alert('请选择要上传的视频文件');
                return;
            }
            
            // 检查文件类型
            if (!videoFile.type.startsWith('video/')) {
                alert('请选择有效的视频文件');
                return;
            }
            
            // 检查文件大小（限制100MB）
            const maxSize = 100 * 1024 * 1024; // 100MB
            if (videoFile.size > maxSize) {
                alert('视频文件过大，请选择小于100MB的文件');
                return;
            }
            
            const progressDiv = document.getElementById('uploadProgress');
            const progressBar = document.getElementById('progressBar');
            const statusDiv = document.getElementById('uploadStatus');
            
            // 显示上传进度
            progressDiv.style.display = 'block';
            progressBar.style.width = '0%';
            statusDiv.textContent = '准备上传...';
            
            // 获取运动类型
            const sportType = document.getElementById('sportType').value;
            
            const formData = new FormData();
            formData.append('video', videoFile);
            formData.append('sportType', sportType);
            
            // 创建XMLHttpRequest以支持进度监控
            const xhr = new XMLHttpRequest();
            
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    progressBar.style.width = percentComplete + '%';
                    statusDiv.textContent = `上传中... ${Math.round(percentComplete)}%`;
                }
            });
            
            xhr.addEventListener('load', function() {
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.code === 0) {
                            progressBar.style.width = '100%';
                            statusDiv.textContent = '✅ 上传成功！正在分析...';
                            
                            // 自动填充结果ID并开始分析
                            document.getElementById('resultId').value = response.data.resultId;
                            
                            // 延迟2秒后自动加载分析
                            setTimeout(() => {
                                progressDiv.style.display = 'none';
                                loadVideoAnalysis();
                            }, 2000);
                            
                        } else {
                            throw new Error(response.message || '上传失败');
                        }
                    } catch (e) {
                        statusDiv.textContent = '❌ 响应解析失败: ' + e.message;
                        statusDiv.style.color = '#f44336';
                    }
                } else {
                    statusDiv.textContent = `❌ 上传失败: HTTP ${xhr.status}`;
                    statusDiv.style.color = '#f44336';
                }
            });
            
            xhr.addEventListener('error', function() {
                statusDiv.textContent = '❌ 网络错误，请检查连接';
                statusDiv.style.color = '#f44336';
            });
            
            xhr.open('POST', 'http://localhost:8085/api/video/upload', true);
            xhr.setRequestHeader('Authorization', `Bearer ${token}`);
            xhr.send(formData);
        }
        
        /**
         * 测试智能播放功能 - 使用模拟数据
         */
        function testSmartPlayback() {
            console.log('🧪 开始测试智能播放功能');
            
            // 创建模拟的播放器配置
            playerConfig = {
                resultId: 'test-demo',
                videoUrl: '#',
                summary: '智能播放功能演示',
                videoDisplayInfo: {
                    videoFileName: 'demo.mp4',
                    videoUrl: '#',
                    problematicFrames: [
                        {
                            frameId: 0,
                            timestamp: 3,
                            severity: '高',
                            issue: '膝关节角度异常',
                            improvement: '保持膝关节轻微弯曲，避免过度伸展',
                            analysisDetails: '演示数据：膝关节角度超出正常范围'
                        },
                        {
                            frameId: 1,
                            timestamp: 8,
                            severity: '中',
                            issue: '摆臂幅度不足',
                            improvement: '增加手臂摆动幅度，保持节奏',
                            analysisDetails: '演示数据：手臂摆动范围偏小'
                        }
                    ],
                    slowMotionSegments: [
                        {
                            startTime: 2,
                            endTime: 5,
                            speed: 0.25,
                            reason: '关键膝关节动作分析',
                            guidance: '仔细观察膝关节的屈伸过程'
                        }
                    ]
                },
                playbackInstructions: [
                    {
                        timestamp: 3,
                        action: 'pause',
                        duration: 3,
                        message: '⚠️ 膝关节角度异常 - 保持膝关节轻微弯曲，避免过度伸展',
                        priority: '高'
                    },
                    {
                        timestamp: 2,
                        action: 'slow',
                        speed: 0.25,
                        message: '🎬 关键膝关节动作分析 - 仔细观察膝关节的屈伸过程',
                        priority: 'normal'
                    },
                    {
                        timestamp: 5,
                        action: 'normal',
                        speed: 1.0,
                        message: '恢复正常播放速度',
                        priority: 'normal'
                    },
                    {
                        timestamp: 8,
                        action: 'pause',
                        duration: 2,
                        message: '⚠️ 摆臂幅度不足 - 增加手臂摆动幅度，保持节奏',
                        priority: '中'
                    }
                ],
                timelineMarkers: [
                    {
                        timestamp: 3,
                        type: 'critical_issue',
                        label: '问题帧 1',
                        description: '膝关节角度异常'
                    },
                    {
                        timestamp: 2,
                        type: 'slow_motion_start',
                        label: '慢放开始',
                        description: '关键膝关节动作分析'
                    },
                    {
                        timestamp: 5,
                        type: 'slow_motion_end',
                        label: '慢放结束',
                        description: '恢复正常速度'
                    },
                    {
                        timestamp: 8,
                        type: 'minor_issue',
                        label: '问题帧 2',
                        description: '摆臂幅度不足'
                    }
                ],
                smartPlayback: {
                    enabled: true,
                    pauseOnProblems: true,
                    slowMotionEnabled: true,
                    autoGuidance: true
                }
            };
            
            // 显示主界面
            showMainContent();
            
            // 创建一个演示视频元素
            videoPlayer = document.getElementById('videoPlayer');
            if (!videoPlayer) {
                console.error('❌ 无法找到视频元素');
                return;
            }
            
            // 设置一个示例视频或创建一个空的视频元素用于演示
            videoPlayer.src = 'data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMWV0bwAAABRtZGF0'; // 最小的MP4文件
            videoPlayer.duration = 20; // 手动设置20秒时长
            
            // 立即渲染界面元素
            console.log('🎬 渲染智能播放界面...');
            
            // 先等一会确保DOM准备好
            setTimeout(() => {
                renderTimelineMarkers();
                renderProblematicFrames();
                renderSlowMotionGuide();
                
                // 强制检查时间轴渲染结果
                const timeline = document.getElementById('timeline');
                if (timeline) {
                    console.log('📊 时间轴元素状态:', {
                        element: timeline,
                        children: timeline.children.length,
                        innerHTML: timeline.innerHTML,
                        style: timeline.style.cssText
                    });
                }
            }, 100);
            
            // 设置智能播放事件
            setupVideoEvents();
            setupPlaybackInstructions();
            
            // 高亮显示时间轴
            const timelineContainer = document.querySelector('.timeline-container');
            if (timelineContainer) {
                timelineContainer.style.border = '3px solid #FF9800';
                timelineContainer.style.boxShadow = '0 0 15px rgba(255, 152, 0, 0.5)';
                setTimeout(() => {
                    timelineContainer.style.border = '';
                    timelineContainer.style.boxShadow = '';
                }, 3000);
            }
            
            alert('🎬 智能播放功能演示已启动！\n\n功能说明：\n• 📊 智能时间轴显示关键时间点（已高亮3秒）\n• 🎯 问题帧列表显示具体问题\n• ⏸️ 播放时会在指定时间暂停和慢放\n• 📍 点击时间轴标记可跳转到对应时间\n\n请查看控制台输出了解详细信息。');
        }
        
        /**
         * 调试时间轴功能
         */
        function debugTimeline() {
            console.log('🔧 开始调试时间轴...');
            
            const timeline = document.getElementById('timeline');
            if (!timeline) {
                alert('❌ 没有找到时间轴元素！');
                return;
            }
            
            console.log('📊 时间轴元素信息:', {
                element: timeline,
                parentElement: timeline.parentElement,
                display: getComputedStyle(timeline).display,
                visibility: getComputedStyle(timeline).visibility,
                width: timeline.offsetWidth,
                height: timeline.offsetHeight,
                children: timeline.children.length
            });
            
            // 强制添加一些测试标记
            timeline.innerHTML = '';
            
            const testMarkers = [
                { position: '10%', color: '#f44336', label: '测试标记1' },
                { position: '30%', color: '#4CAF50', label: '测试标记2' },
                { position: '60%', color: '#2196F3', label: '测试标记3' },
                { position: '80%', color: '#FF9800', label: '测试标记4' }
            ];
            
            testMarkers.forEach((marker, index) => {
                const markerElement = document.createElement('div');
                markerElement.style.cssText = `
                    position: absolute;
                    top: -2px;
                    left: ${marker.position};
                    width: 6px;
                    height: calc(100% + 4px);
                    background: ${marker.color};
                    border-radius: 3px;
                    cursor: pointer;
                    z-index: 5;
                `;
                markerElement.title = marker.label;
                markerElement.onclick = () => alert(`点击了${marker.label}`);
                
                timeline.appendChild(markerElement);
                console.log(`✅ 添加测试标记 ${index + 1}: ${marker.label} at ${marker.position}`);
            });
            
            alert(`🔧 时间轴调试完成！\n\n检查结果：\n• 时间轴元素: ${timeline ? '✅' : '❌'}\n• 添加了 ${testMarkers.length} 个测试标记\n• 宽度: ${timeline.offsetWidth}px\n• 高度: ${timeline.offsetHeight}px\n\n请查看控制台了解详细信息。`);
        }
        
        function testLogin() {
            const token = document.getElementById('token').value;
            
            if (!token) {
                alert('请先输入Token');
                return;
            }
            
            // 测试token是否有效
            fetch('http://localhost:8085/uaa/auth/current-user', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    } else {
                        throw new Error('Token无效或已过期');
                    }
                })
                .then(data => {
                    alert('✅ Token验证成功！用户: ' + (data.data?.username || '未知'));
                })
                .catch(error => {
                    alert('❌ Token验证失败: ' + error.message + '\n\n请通过以下方式获取有效token:\n1. POST localhost:8085/uaa/auth/login 登录\n2. 复制返回的token到此处');
                });
        }
        
        function initializePlayer() {
            const videoInfo = playerConfig.videoDisplayInfo;
            const resultId = playerConfig.resultId;
            const token = document.getElementById('token').value;
            
            console.log('正在初始化智能播放器，结果ID:', resultId);
            console.log('播放器配置:', playerConfig);
            
            // 设置视频源（带认证）
            videoPlayer = document.getElementById('videoPlayer');
            
            if (!videoPlayer) {
                console.error('❌ 无法找到视频元素!');
                showError('无法找到视频播放器元素');
                return;
            }
            
            console.log('✅ 找到视频元素:', videoPlayer);
            
            // 清理之前的事件监听器
            videoPlayer.removeEventListener('loadeddata', handleVideoLoaded);
            videoPlayer.removeEventListener('error', handleVideoError);
            videoPlayer.removeEventListener('loadstart', handleVideoLoadStart);
            videoPlayer.removeEventListener('canplay', handleVideoCanPlay);
            
            // 先设置视频事件监听器
            videoPlayer.addEventListener('loadeddata', handleVideoLoaded);
            videoPlayer.addEventListener('error', handleVideoError);
            videoPlayer.addEventListener('loadstart', handleVideoLoadStart);
            videoPlayer.addEventListener('canplay', handleVideoCanPlay);
            
            // 设置其他播放器事件
            setupVideoEvents();
            
            // 为视频请求添加认证头
            console.log('正在请求视频文件:', `http://localhost:8085/api/video/play/${resultId}`);
            fetch(`http://localhost:8085/api/video/play/${resultId}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => {
                    console.log('视频请求响应状态:', response.status);
                    if (response.ok) {
                        return response.blob();
                    } else {
                        throw new Error(`视频加载失败，HTTP状态码: ${response.status}`);
                    }
                })
                .then(blob => {
                    console.log('✅ 视频blob创建成功，大小:', (blob.size / 1024 / 1024).toFixed(2) + 'MB');
                    console.log('视频blob类型:', blob.type);
                    
                    const videoUrl = URL.createObjectURL(blob);
                    console.log('🎬 设置视频源:', videoUrl);
                    
                    // 设置视频源并等待加载
                    videoPlayer.src = videoUrl;
                    
                    // 强制加载
                    videoPlayer.load();
                    
                    console.log('视频元素状态检查:');
                    console.log('- src:', videoPlayer.src);
                    console.log('- readyState:', videoPlayer.readyState);
                    console.log('- networkState:', videoPlayer.networkState);
                    
                    // 显示主界面
                    showMainContent();
                    
                    // 设置一个超时检查
                    setTimeout(() => {
                        if (videoPlayer.readyState === 0) {
                            console.warn('⚠️ 视频30秒后仍未开始加载');
                            showMessage('视频加载可能遇到问题，请检查浏览器控制台', 'warning');
                        }
                    }, 30000);
                })
                .catch(error => {
                    console.error('❌ 视频加载失败:', error);
                    showError('视频加载失败: ' + error.message);
                                  });
        }
        
        // 视频事件处理函数
        function handleVideoLoaded() {
            console.log('✅ 视频数据加载完成');
            console.log('视频时长:', videoPlayer.duration, '秒');
            console.log('视频尺寸:', videoPlayer.videoWidth + 'x' + videoPlayer.videoHeight);
            showMessage('视频加载完成！', 'success');
            
            // 渲染界面元素
            renderTimelineMarkers();
            renderProblematicFrames();
            renderSlowMotionGuide();
        }
        
        function handleVideoError(e) {
            console.error('❌ 视频播放错误:', e);
            console.error('错误对象:', e.target.error);
            let errorMsg = '未知错误';
            let suggestions = '';
            
            if (e.target.error) {
                switch(e.target.error.code) {
                    case 1: 
                        errorMsg = '视频加载被中止'; 
                        suggestions = '尝试重新加载页面或检查网络连接';
                        break;
                    case 2: 
                        errorMsg = '网络错误'; 
                        suggestions = '检查网络连接或服务器状态';
                        break;
                    case 3: 
                        errorMsg = '视频解码失败'; 
                        suggestions = '视频文件可能已损坏，请重新生成分析结果';
                        break;
                    case 4: 
                        errorMsg = '视频格式不支持'; 
                        suggestions = `当前浏览器不支持此视频格式。
建议解决方案：
1. 尝试使用Chrome或Firefox浏览器
2. 检查视频文件是否为标准MP4格式
3. 联系管理员检查视频编码设置

浏览器支持信息：
- H.264编码: ${videoPlayer.canPlayType('video/mp4; codecs="avc1.42E01E"')}
- WebM格式: ${videoPlayer.canPlayType('video/webm')}`;
                        break;
                }
            }
            
            // 如果是格式不支持，尝试打开测试页面
            if (e.target.error && e.target.error.code === 4) {
                const testUrl = `${window.location.origin}/video-test.html`;
                showError(`${errorMsg}

${suggestions}

<br><br>
<a href="${testUrl}" target="_blank" style="color: #007bff; text-decoration: underline;">
🔧 点击这里打开视频诊断工具进行详细检测
</a>`);
            } else {
                showError(`视频播放出错: ${errorMsg}${suggestions ? '\n\n建议: ' + suggestions : ''}`);
            }
        }
        
        function handleVideoLoadStart() {
            console.log('🔄 开始加载视频...');
        }
        
        function handleVideoCanPlay() {
            console.log('✅ 视频可以开始播放');
            console.log('视频就绪状态:', videoPlayer.readyState);
        }
        
        function setupVideoEvents() {
            videoPlayer.addEventListener('timeupdate', updateVideoInfo);
            videoPlayer.addEventListener('loadedmetadata', setupPlaybackInstructions);
        }
        
        function setupPlaybackInstructions() {
            console.log('🎬 设置智能播放指令');
            console.log('播放器配置:', playerConfig);
            
            const instructions = playerConfig.playbackInstructions;
            if (!instructions || instructions.length === 0) {
                console.log('⚠️ 没有找到播放指令');
                return;
            }
            
            console.log(`✅ 发现 ${instructions.length} 个智能播放指令:`, instructions);
            
            // 用于跟踪已执行的指令，避免重复执行
            const executedInstructions = new Set();
            
            videoPlayer.addEventListener('timeupdate', function() {
                const currentTime = videoPlayer.currentTime;
                
                instructions.forEach((instruction, index) => {
                    const timeDiff = Math.abs(currentTime - instruction.timestamp);
                    const instructionKey = `${index}_${instruction.timestamp}_${instruction.action}`;
                    
                    if (timeDiff < 0.2 && !executedInstructions.has(instructionKey)) { // 200ms 容差，避免重复执行
                        console.log(`🎯 执行指令 @${instruction.timestamp}s:`, instruction);
                        executeInstruction(instruction);
                        executedInstructions.add(instructionKey);
                        
                        // 清理已过期的指令记录（避免内存泄漏）
                        setTimeout(() => {
                            executedInstructions.delete(instructionKey);
                        }, 2000);
                    }
                });
            });
        }
        
        function executeInstruction(instruction) {
            switch (instruction.action) {
                case 'slow':
                    videoPlayer.playbackRate = instruction.speed;
                    showMessage(instruction.message, 'info');
                    break;
                case 'pause':
                    videoPlayer.pause();
                    showMessage(instruction.message, 'warning');
                    setTimeout(() => {
                        videoPlayer.play();
                    }, instruction.duration * 1000);
                    break;
                case 'normal':
                    videoPlayer.playbackRate = 1.0;
                    break;
                case 'highlight':
                    highlightCurrentFrame();
                    break;
            }
        }
        
        function renderTimelineMarkers() {
            console.log('🕒 渲染时间轴标记');
            const timeline = document.getElementById('timeline');
            if (!timeline) {
                console.error('❌ 没有找到时间轴元素');
                return;
            }
            
            timeline.innerHTML = '';
            
            const markers = playerConfig.timelineMarkers;
            if (!markers || markers.length === 0) {
                console.log('⚠️ 没有找到时间轴标记');
                return;
            }
            
            const videoDuration = getVideoDuration();
            console.log(`✅ 渲染 ${markers.length} 个时间轴标记，视频时长: ${videoDuration}s`);
            console.log('时间轴标记:', markers);
            
            markers.forEach((marker, index) => {
                const markerElement = document.createElement('div');
                markerElement.className = `timeline-marker ${marker.type.replace('_', '-')}`;
                markerElement.style.left = `${(marker.timestamp / videoDuration) * 100}%`;
                markerElement.title = `${marker.label}: ${marker.description}`;
                
                console.log(`📍 添加标记 ${index + 1}: @${marker.timestamp}s (${((marker.timestamp / videoDuration) * 100).toFixed(1)}%) - ${marker.label}`);
                
                markerElement.addEventListener('click', () => {
                    videoPlayer.currentTime = marker.timestamp;
                    showMessage(marker.description, 'info');
                });
                
                timeline.appendChild(markerElement);
            });
        }
        
        function renderProblematicFrames() {
            const container = document.getElementById('problematicFrames');
            container.innerHTML = '';
            
            const frames = playerConfig.videoDisplayInfo.problematicFrames;
            
            // 添加统计信息
            const reanalyzedCount = frames.filter(frame => 
                frame.improvement && frame.improvement.includes('[重新分析]')).length;
            
            if (reanalyzedCount > 0) {
                const statsElement = document.createElement('div');
                statsElement.style.cssText = `
                    margin-bottom: 15px;
                    padding: 12px;
                    background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
                    border-radius: 8px;
                    border-left: 4px solid #4caf50;
                    text-align: center;
                `;
                statsElement.innerHTML = `
                    <div style="font-weight: 600; color: #2e7d32; margin-bottom: 4px;">
                        🎯 智能优化统计
                    </div>
                    <div style="font-size: 14px; color: #388e3c;">
                        <strong>${reanalyzedCount}</strong> 个问题帧已通过单帧重新分析进行精度优化
                    </div>
                `;
                container.appendChild(statsElement);
            }
            
            frames.forEach((frame, index) => {
                const isReanalyzed = frame.improvement && frame.improvement.includes('[重新分析]');
                
                const frameElement = document.createElement('div');
                frameElement.className = `problem-frame severity-${frame.severity === '高' ? 'high' : frame.severity === '中' ? 'medium' : 'low'}`;
                
                // 如果经过重新分析，添加特殊样式
                if (isReanalyzed) {
                    frameElement.style.background = 'linear-gradient(135deg, #f8f9fa 0%, #e3f2fd 100%)';
                    frameElement.style.borderLeft = '4px solid #2196f3';
                    frameElement.style.position = 'relative';
                }
                
                const reanalysisIcon = isReanalyzed ? '🔄 ' : '';
                const reanalysisBadge = isReanalyzed ? 
                    '<span style="background: #2196f3; color: white; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 8px;">已优化</span>' : '';
                
                frameElement.innerHTML = `
                    <div class="frame-time">⏰ ${reanalysisIcon}${frame.timestamp.toFixed(2)}秒 (第${frame.frameId}帧) ${reanalysisBadge}<span class="status-indicator ${frame.severity === '高' ? 'high' : frame.severity === '中' ? 'medium' : 'low'}"></span></div>
                    <div class="frame-issue">❌ ${frame.issueDescription}</div>
                    <div class="frame-improvement">💡 ${frame.improvement}</div>
                    ${isReanalyzed ? '<div style="margin-top: 8px; padding: 8px; background: rgba(33, 150, 243, 0.1); border-radius: 4px; font-size: 12px; color: #1976d2;">✨ 此帧已通过智能重新分析优化，提高了检测精度</div>' : ''}
                `;
                
                frameElement.addEventListener('click', () => {
                    jumpToFrame(frame.timestamp);
                });
                
                container.appendChild(frameElement);
            });
        }
        
        function renderSlowMotionGuide() {
            console.log('🐌 渲染慢放指导');
            const container = document.getElementById('slowMotionGuide');
            if (!container) {
                console.error('❌ 没有找到慢放指导容器');
                return;
            }
            
            container.innerHTML = '';
            
            const segments = playerConfig.videoDisplayInfo.slowMotionSegments;
            if (!segments || segments.length === 0) {
                console.log('⚠️ 没有找到慢放片段');
                container.innerHTML = '<p style="color: #666; text-align: center;">暂无慢放指导</p>';
                return;
            }
            
            console.log(`✅ 渲染 ${segments.length} 个慢放片段`);
            
            segments.forEach((segment, index) => {
                const segmentElement = document.createElement('div');
                segmentElement.style.cssText = `
                    margin-bottom: 15px;
                    padding: 12px;
                    background: #f8f9fa;
                    border-radius: 8px;
                    border-left: 4px solid #2196f3;
                `;
                
                segmentElement.innerHTML = `
                    <p><strong>🎬 ${segment.reason || '慢放片段'}</strong></p>
                    <p>⏰ ${segment.startTime.toFixed(2)}s - ${segment.endTime.toFixed(2)}s</p>
                    <p>🐌 播放速度: ${(segment.speed || segment.playbackSpeed || 0.5).toFixed(2)}x</p>
                    <p style="margin-top: 8px; color: #666;">💡 ${segment.guidance || '观察动作细节'}</p>
                `;
                
                console.log(`📍 添加慢放片段 ${index + 1}: ${segment.startTime}s-${segment.endTime}s @${segment.speed || 0.5}x`);
                container.appendChild(segmentElement);
            });
        }
        
        function updateVideoInfo() {
            const currentTime = videoPlayer.currentTime;
            const fps = playerConfig.videoDisplayInfo.videoInfo ? playerConfig.videoDisplayInfo.videoInfo.fps || 30 : 30;
            const currentFrame = Math.floor(currentTime * fps);
            
            document.getElementById('currentFrame').textContent = `帧: ${currentFrame}`;
            document.getElementById('currentTime').textContent = `时间: ${currentTime.toFixed(2)}s`;
            document.getElementById('playbackSpeed').textContent = `速度: ${videoPlayer.playbackRate.toFixed(2)}x`;
        }
        
        function jumpToFrame(timestamp) {
            videoPlayer.currentTime = timestamp;
            videoPlayer.play();
            showMessage(`跳转到 ${timestamp.toFixed(2)}秒`, 'info');
        }
        
        function playVideo() {
            videoPlayer.play();
        }
        
        function pauseVideo() {
            videoPlayer.pause();
        }
        
        function setSpeed(speed) {
            videoPlayer.playbackRate = speed;
            showMessage(`播放速度设置为 ${speed}x`, 'info');
        }
        
        function getVideoDuration() {
            const duration = videoPlayer && videoPlayer.duration ? videoPlayer.duration : 20; // 默认20秒
            console.log('📏 视频时长:', duration + 's');
            return duration;
        }
        
        function showMessage(message, type) {
            // 简单的消息提示
            const overlay = document.querySelector('.video-overlay');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = message;
            messageDiv.style.cssText = `
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: ${type === 'warning' ? '#ff9800' : type === 'error' ? '#f44336' : '#4CAF50'};
                color: white;
                padding: 15px 25px;
                border-radius: 8px;
                font-weight: 600;
                z-index: 1000;
            `;
            
            overlay.appendChild(messageDiv);
            
            setTimeout(() => {
                messageDiv.remove();
            }, 3000);
        }
        
        function highlightCurrentFrame() {
            const overlay = document.querySelector('.video-overlay');
            overlay.style.border = '3px solid #ff9800';
            setTimeout(() => {
                overlay.style.border = 'none';
            }, 1000);
        }
        
        function showLoading() {
            document.getElementById('inputSection').style.display = 'none';
            document.getElementById('mainContent').style.display = 'none';
            document.getElementById('errorSection').style.display = 'none';
            document.getElementById('loadingSection').style.display = 'block';
        }
        
        function showMainContent() {
            document.getElementById('inputSection').style.display = 'none';
            document.getElementById('loadingSection').style.display = 'none';
            document.getElementById('errorSection').style.display = 'none';
            document.getElementById('mainContent').style.display = 'grid';
        }
        
        function showError(message) {
            document.getElementById('inputSection').style.display = 'none';
            document.getElementById('loadingSection').style.display = 'none';
            document.getElementById('mainContent').style.display = 'none';
            document.getElementById('errorSection').style.display = 'block';
            document.getElementById('errorMessage').textContent = message;
        }
        
        function quickLogin() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
            
            // 调用登录API
            fetch('http://localhost:8085/uaa/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            })
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    } else {
                        throw new Error('登录失败，请检查用户名密码');
                    }
                })
                .then(data => {
                    if (data.code === 0 && data.data?.token) {
                        // 自动填充token
                        document.getElementById('token').value = data.data.token;
                        
                        // 保存到本地存储
                        localStorage.setItem('authToken', data.data.token);
                        localStorage.setItem('username', username);
                        
                        alert('✅ 登录成功！Token已自动填充');
                    } else {
                        throw new Error('登录失败: ' + (data.message || '未知错误'));
                    }
                })
                .catch(error => {
                    alert('❌ 登录失败: ' + error.message);
                });
        }
        
        function loadStoredToken() {
            // 从本地存储加载token
            const storedToken = localStorage.getItem('authToken');
            const storedUsername = localStorage.getItem('username');
            
            if (storedToken) {
                document.getElementById('token').value = storedToken;
            }
            
            if (storedUsername) {
                document.getElementById('username').value = storedUsername;
            }
        }
        
        function makeAuthenticatedRequest(url, options = {}) {
            const token = document.getElementById('token').value;
            
            const defaultOptions = {
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                    ...options.headers
                }
            };
            
            return fetch(url, { ...options, headers: defaultOptions.headers });
        }
        
        // 打开AI指导页面
        function openAiGuidance() {
            const resultId = document.getElementById('resultId').value.trim();
            const sportType = document.getElementById('sportType').value;
            const token = document.getElementById('token').value.trim();
            
            if (!resultId) {
                alert('请先输入分析结果ID');
                return;
            }
            
            // 构建AI指导页面URL，传递参数
            const params = new URLSearchParams();
            params.append('resultId', resultId);
            params.append('sportType', sportType);
            if (token) {
                localStorage.setItem('authToken', token); // 保存token到本地存储
            }
            
            const aiGuidanceUrl = `ai-guidance.html?${params.toString()}`;
            window.open(aiGuidanceUrl, '_blank');
            
            console.log('🤖 打开AI指导页面:', aiGuidanceUrl);
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('智能视频播放器初始化完成');
            
            // 加载存储的token
            loadStoredToken();
            
            // 添加快捷键支持
            document.addEventListener('keydown', function(e) {
                if (videoPlayer && !videoPlayer.paused) {
                    switch(e.key) {
                        case ' ': // 空格键暂停/播放
                            e.preventDefault();
                            if (videoPlayer.paused) {
                                playVideo();
                            } else {
                                pauseVideo();
                            }
                            break;
                        case '1': // 数字1：0.25x速度
                            e.preventDefault();
                            setSpeed(0.25);
                            break;
                        case '2': // 数字2：0.5x速度
                            e.preventDefault();
                            setSpeed(0.5);
                            break;
                        case '3': // 数字3：正常速度
                            e.preventDefault();
                            setSpeed(1.0);
                            break;
                    }
                }
            });
        });
    </script>
</body>
</html> 